package com.luoran.bartalks.api;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.core.AppUser;
import com.luoran.bartalks.entity.biz.BtPosition;
import com.luoran.bartalks.service.IBtPositionService;
import com.luoran.bartalks.utils.MapDistanceCalculation;
import com.luoran.bartalks.utils.MapKeyComparator;

@RestController
@RequestMapping("/api/address")
public class AddressApi {

	@Autowired
	private IBtPositionService positionService;

	/**
	 * 根据经纬度查询出当前用户所在公司下距离最近的位置列表
	 * 
	 * @param lat
	 * @param lng
	 * @return
	 */
	@RequestMapping("my")
	public String myPosition(String lat, String lng) {
		double lat1 = Double.parseDouble(lat);
		double lng1 = Double.parseDouble(lng);
		Map<Double, String> map = new TreeMap<Double, String>();
		ArrayList<Object> array = new ArrayList<>();
		JSONObject res = new JSONObject();
		String companyId = AppUser.get().getCompanyId();
		List<BtPosition> Positions = positionService.getPositionByCompanyId(companyId);
		for (BtPosition btPosition : Positions) {
			double lat2 = Double.parseDouble(btPosition.getLatitude());
			double lng2 = Double.parseDouble(btPosition.getLongitude());
			// 2点距离比较
			double s = MapDistanceCalculation.getDistance(lat1, lng1, lat2, lng2);
			if (s <= 10000) {
				map.put(s, btPosition.getId());
			}
		}
		if (map.isEmpty()) {
			res.put("msg", "10公里范围内未找到公司指定地点");
			res.put("state", false);
		} else {
			// map比较器
			Map<Double, String> resultMap = MapKeyComparator.sortMapByKey(map);
			for (Map.Entry<Double, String> entry : resultMap.entrySet()) {
				BtPosition Position = positionService.getPositionById(entry.getValue());
				array.add(Position);
			}
			res.put("data", array);
			res.put("state", true);
		}
		return res.toJSONString();
	}

}
